using System;
using System.Collections.Generic;
using System.Windows.Threading;

namespace Silvery
{
    /// <summary>
    /// 资源管理器
    /// </summary>
    public sealed class ResourceManager : List<IResStream>, IResourceManager
    {
        static ResourceManager current;
        public static ResourceManager Current
        {
            get
            {

                if (current == null)
                    current = new ResourceManager();
                return current;
            }
        }
        /// <summary>
        /// 默认一个资源可以存在的时间，默认为10分钟
        /// 20分钟过后就会销毁，使得用户重新下载
        /// 如果是0的话，则永远不会因为时间造成销毁
        /// </summary>
        public TimeSpan MaxCacheTimeSpan { get; set; }
        public TimeSpan MaxInspectTimeSpan
        {
            get { return loop.Interval; }
            set
            {
                loop.Interval = value;
            }
        }
        DispatcherTimer loop = new DispatcherTimer();
        private ResourceManager()
        {
            MaxCacheTimeSpan = TimeSpan.FromMinutes(10);

            MaxInspectTimeSpan = TimeSpan.FromSeconds(30);
            loop.Tick += new EventHandler(loop_Tick);
            loop.Start();
        }
        void loop_Tick(object sender, EventArgs e)
        {
            IResStream[] array = new IResStream[this.Count];
            this.CopyTo(array);

            foreach (var item in array)
            {
                if (item.TimeSheet.LastCallTimeSpan >= MaxCacheTimeSpan && MaxCacheTimeSpan.Ticks != 0)
                    this.Remove(item);
                //else
                //    if (item.UsingCount == 0)
                //        this.Remove(item);
                
            }
            if(array.Length>0)
                GC.Collect();
            array = null;
        }
        public new void Remove(IResStream item)
        {
            item.Dispose();
            this.Remove(item);
            
        }
        public IResStream Contains(Uri uri)
        {
            IResStream[] array = new IResStream[this.Count];
            this.CopyTo(array);
            foreach (var item in array)
            {
                var i = Uri.Compare(uri, item.ResouceUri, UriComponents.Path, UriFormat.SafeUnescaped, StringComparison.Ordinal);
                if (i == 0)
                    return item;
            }
            return null;
        }
    }
}
